﻿// // ******************************************************************
// //       /\ /|       @file       LanguageCommandHandler.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-07 10:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-07 10:11 Await
// // ******************************************************************

using AutomaticSubtitles.Service.Application.Language.Commands;
using AutomaticSubtitles.Service.DataAccess.Model;
using AutomaticSubtitles.Service.Domain.Config;

namespace AutomaticSubtitles.Service.Application.Language;

public class LanguageCommandHandler(ILanguageRepository repository) : BaseAutoService
{
    [EventHandler]
    public async Task Handle2Async(AddLanguageCommand command)
    {
        var countAsync = await repository.GetCountAsync(x => x.Key == command.data.key);
        if (countAsync > 0)
            throw new ArgumentException(ReturnMessage(Repeat));
        var config = new Auto_Language(BasicsHelper.GetId())
        {
            Key = command.data.key,
            IsSkip = command.data.isSkip
        };
        await repository.AddAsync(config);
        command.Result = 1;
    }

    [EventHandler]
    public async Task HandleAsync(UpdateLanguageCommand command)
    {
        var countAsync = await repository.GetCountAsync(x => x.Key == command.data.key && x.Id != command.data.id);
        if (countAsync > 0)
            throw new ArgumentException("该语言已存在");
        var findAsync = await repository.FindAsync(x => x.Id == command.data.id) ?? throw new ArgumentException(ReturnMessage(NoExistent));
        findAsync.Key = command.data.key;
        findAsync.IsSkip = command.data.isSkip;
        await repository.UpdateAsync(findAsync);
        command.Result = 1;
    }

    [EventHandler]
    public async Task HandleAsync(DeleteLanguageCommand command)
    {
        var findAsync = await repository.FindAsync(x => x.Id == command.id) ?? throw new ArgumentException(ReturnMessage(NoExistent));
        // await repository.RemoveAsync(command.id);
        await repository.RemoveAsync(findAsync);
        command.Result = 1;
    }
}